<template>
  <div class="editMedicalRecord addEditPage">
    <amsp-card class="cardsBoxInfo" title="基本信息">
      <el-row :gutter="20">
        <el-col :span="8"><span class="k">姓名</span><span class="v">{{patientInfo.name}}</span></el-col>
        <el-col :span="8"><span class="k">性别</span><span class="v">{{patientInfo.sex}}</span></el-col>
        <el-col :span="8"><span class="k">年龄</span><span class="v">{{patientInfo.age}}</span></el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8"><span class="k">身份证号</span><span class="v">{{patientInfo.identityCard}}</span></el-col>
        <el-col :span="8"><span class="k">联系电话</span><span class="v">{{patientInfo.phoneNumber}}</span></el-col>
      </el-row>

    </amsp-card>

    <amsp-card class="record" title="患者影像信息">
      <div class="btns" slot="btns" v-if="getUserType != 1"><el-button type="primary" @click="fileList3mf=[];fileListct=[];fileList3mfScreenshot=[];fileListctScreenshot=[];pop.pop1.title='新增影像信息';pop.pop1.flag=true">新增</el-button></div>

      <div class="tableMain">
        <!-- <el-table :data="tableData.listInfo1.list" stripe fixed :height="tableData.listInfo1.height" style="width: 100%"> -->
        <el-table :data="tableData.listInfo1.list" ref="eltable" stripe fixed height="100%" style="width: 100%">
          <el-table-column fixed="left" label="序号" width="80">
              <template slot-scope="scope">
                {{ (tableData.listInfo1.form.pageNum - 1) * tableData.listInfo1.form.pageSize + scope.$index + 1 }}
              </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip :prop="KEYS.key1" label="病情概况">
            <template slot-scope="scope">
              <div>{{scope.row[KEYS.key1]}}</div>
              <!--<div @click="copyUrl(scope.row)" style="color: #409EFF; cursor: pointer;">{{scope.row[KEYS.key1]}}</div>-->
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip :prop="KEYS.key3" label="影像模型文件">
            <template slot-scope="scope">
              <span v-for="(a,b) in scope.row[`${KEYS.key3}3mf`]" :key="b">
                {{a.name | noSuffix}}<template v-if="scope.row[`${KEYS.key3}3mf`].length-1 != b">,</template>
              </span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip :prop="KEYS.key10" label="CT文件">
            <template slot-scope="scope">
              <span v-for="(a,b) in scope.row[`${KEYS.key10}ct`]" :key="b">
                {{a.name | noSuffix}}<template v-if="scope.row[`${KEYS.key10}ct`].length-1 != b">,</template>
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column show-overflow-tooltip :prop="KEYS.key6" label="创建人" width="100"></el-table-column> -->
          <el-table-column show-overflow-tooltip :prop="KEYS.key7" label="创建时间" width="180"></el-table-column>
          <!-- <el-table-column show-overflow-tooltip :prop="KEYS.key8" label="最后修改人" width="100"></el-table-column> -->
          <el-table-column show-overflow-tooltip :prop="KEYS.key9" label="最后修改时间" width="180"></el-table-column>
          <el-table-column fixed="right" label="操作" width="280">
            <template slot-scope="scope">
              <el-tooltip effect="light" content="下载二维码" placement="left">
                <i class="handleBtn amsp el-amsp-erweimafenxiang" @click="downFile(scope.row.screenageQrcodeUrl,scope.row.urlPrefix)"></i>
              </el-tooltip>
              <el-tooltip effect="light" content="复制链接" placement="left">
                <i class="handleBtn amsp el-icon-share" @click="copyUrl(scope.row)"></i>
              </el-tooltip>
              <el-tooltip effect="light" content="预览" placement="left">
                <i class="handleBtn amsp el-amsp-yulan2" @click="lookModel(scope.row)"></i>
              </el-tooltip>
              <el-tooltip effect="light" content="编辑" placement="left" v-if="getUserType != 1">
                <i class="handleBtn el-icon-edit-outline" @click="editFormRecordManage(scope.row)"></i>
              </el-tooltip>
              <el-tooltip effect="light" content="生成图文报告" placement="left">
                <i class="handleBtn amsp el-amsp-bianji2" style="font-size: 18px;" @click="$router.push({name: 'patientReport', query: {id: scope.row.id,patientId:prev.id,hospitalName:scope.row.hospitalName}})"></i>
              </el-tooltip>
              <el-tooltip effect="light" content="上传图文报告" placement="left" >
                <i class="handleBtn amsp el-icon-upload" style="font-size: 18px;" @click="uploadPDFShow(scope.row)"></i>
              </el-tooltip>
              <el-tooltip effect="light" content="预览图文报告" placement="left" >
                <i class="handleBtn amsp el-amsp-pdf2" style="font-size: 18px;" @click="previewFile(scope.row.graphicReport,scope.row.urlPrefix)"></i>
              </el-tooltip>
              <!-- <el-tooltip effect="light" content="下载图文报告" placement="left" >
                <i class="handleBtn amsp el-icon-download" style="font-size: 18px;" @click="downFile(scope.row.graphicReport,scope.row.urlPrefix)"></i>
              </el-tooltip> -->
              <el-tooltip effect="light" content="删除" placement="left" v-if="getUserType != 1">
                <i class="handleBtn el-icon-delete" style="color: red" @click="deletRecordManage(scope.row)"></i>
                </el-tooltip>
            </template>
          </el-table-column>
      </el-table>
      </div>
      <amsp-page 
        tableName="listInfo1"
        :pageSize="tableData.listInfo1.form.pageSize"
        @changeSize="changeSize($event, 'listInfo1')"
        @setPage="changePage($event, 'listInfo1')"
        :tableForm="tableData.listInfo1.form"
        @toFirst="changePage(1, 'listInfo1')"
        @toEnd="changePage(tableData.listInfo1.form.pages, 'listInfo1')"/>
    </amsp-card>

    <div class="baseFormBtns">
      <el-button round type="primary" @click="$router.back()">完成</el-button>
    </div>
  <amsp-pop class="addEditMedicalRecord" ref="addEditMedicalRecord"  :title="pop.pop1.title" width="560px":visible.sync="pop.pop1.flag" :before-close="closeAddEdit">
      <div class="addEditForm">
      <el-form class="addEditFormMedicalRecord" ref="addEditFormMedicalRecord" :model="pop.pop1.form" :rules="RULES"  label-position="left" label-width="90px" @submit.native.prevent>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院" :prop="KEYS.key11">
              <el-input placeholder="请输入医院" v-model="pop.pop1.form[KEYS.key11]"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" :prop="KEYS.key12">
              <el-input placeholder="请输入科室" v-model="pop.pop1.form[KEYS.key12]"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="影像类型" :prop="KEYS.key13">
              <el-input placeholder="请输入影像类型" v-model="pop.pop1.form[KEYS.key13]"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重建组织" :prop="KEYS.key14">
              <el-input placeholder="请输入重建组织" v-model="pop.pop1.form[KEYS.key14]"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
          
          <el-form-item label="病情概况" :prop="KEYS.key1">
            <el-input type="textarea" maxlength="200" rows="4" show-word-limit placeholder="请简要说明患者临床诊断病例特征" v-model="pop.pop1.form[KEYS.key1]"></el-input>
          </el-form-item>
          <el-form-item label="上传影像模型文件" :prop="KEYS.key3" label-width="140px">
            <amsp-up-file v-if="pop.pop1.flag" :accept="['.3mf']" :fileListS="fileList3mf" @onChange="onChange($event, KEYS.key3)"></amsp-up-file>
          </el-form-item>

          <el-form-item label="Slice Increment" :prop="KEYS.key17" label-width="140px">
            <el-input type="number" placeholder="请输入Slice Increment" v-model="pop.pop1.form[KEYS.key17]"></el-input>
          </el-form-item>

          <el-form-item label="Pixel Size" :prop="KEYS.key21" label-width="140px">
            <el-input type="number" placeholder="请输入Pixel Size" v-model="pop.pop1.form[KEYS.key21]"></el-input>
          </el-form-item>

          <el-form-item label="Zmax" :prop="KEYS.key18" label-width="140px">
            <el-input type="number" placeholder="请输入Zmax" v-model="pop.pop1.form[KEYS.key18]"></el-input>
          </el-form-item>
          <el-form-item label="Xmax" :prop="KEYS.key19" label-width="140px">
            <el-input type="number" placeholder="请输入Xmax" v-model="pop.pop1.form[KEYS.key19]"></el-input>
          </el-form-item>
          <el-form-item label="Ymax" :prop="KEYS.key20" label-width="140px">
            <el-input type="number" placeholder="请输入Ymax" v-model="pop.pop1.form[KEYS.key20]"></el-input>
          </el-form-item>

          <el-form-item label="上传CT压缩文件" :prop="KEYS.key10" label-width="140px">
            <amsp-up-file v-if="pop.pop1.flag" :accept="['.zip']" :fileListS="fileListct" @onChange="onChange($event, KEYS.key10)" :limit="1"></amsp-up-file>
          </el-form-item>
          <!-- <el-form-item label="上传模型的截图" :prop="KEYS.key15" label-width="140px">
            <amsp-up-file v-if="pop.pop1.flag" :accept="['.jpg','.png']" :fileListS="fileList3mfScreenshot" @onChange="onChange($event, KEYS.key15)"></amsp-up-file>
          </el-form-item>
          <el-form-item label="上传CT的截图" :prop="KEYS.key16" label-width="140px">
            <amsp-up-file v-if="pop.pop1.flag" :accept="['.jpg','.png']" :fileListS="fileListctScreenshot" @onChange="onChange($event, KEYS.key16)"></amsp-up-file>
          </el-form-item> -->
      </el-form>
      <div class="baseFormBtns" id="baseFormBtns">
        <el-button round @click="closeAddEdit">取消</el-button>
        <el-button round type="primary" @click="addMedicalRecord">确定</el-button>
      </div>
    </div>
  </amsp-pop>
    <amsp-pop class="addEditMedicalRecord" ref="addEditMedicalRecord"  :title="pop.pop2.title" width="560px":visible.sync="pop.pop2.flag" :before-close="closePDFPoP">
      <div class="addEditForm">
        <el-form class="addEditFormMedicalRecord" ref="upLoadPDFRecord" :model="pop.pop2.form"  label-position="left" label-width="90px" @submit.native.prevent>
          <el-form-item label="图文报告(pdf格式):" prop="file" label-width="140px">
            <!--<amsp-up-file v-if="pop.pop2.flag" :accept="['.pdf']" :fileListS="fileListct" @onChange="onChange2($event, 'file')" :limit="1"></amsp-up-file>-->
            <input type="file" ref="fileId" id="uploadFile_input"  @change="getFile">
          </el-form-item>
        </el-form>
        <div class="baseFormBtns" id="">
          <el-button round @click="closePDFPoP">取消</el-button>
          <el-button round type="primary" @click="uploadGraphicReport">确定</el-button>
        </div>
      </div>
    </amsp-pop>
  </div>
</template>

<script>
import {addMedicalRecord, editMedicalRecord, pageQueryMedicalRecord,uploadQraphicReport} from '@/depends/api/medicalRecord'
import {queryPatientOne} from '@/depends/api/patient'
import {deepCopy, downFile,previewFile} from '@/utils/tools/tools'
import {KEYS_RULES_MIXIN, KEYS} from './component/keys.js'
import {mapGetters} from 'vuex'


export default {
  mixins: [KEYS_RULES_MIXIN],
  components: {
  },
  // provide () {
  //   return {
  //     vMain: this
  //   }
  // },
  data() {
    return {
      prev: this.$route.query,
      fileList3mf: [],
      fileListct: [],
      fileList3mfScreenshot: [],
      fileListctScreenshot: [],
      patientInfo: {},
      pop: {
        pop1: {
          flag: false,
          title: '新增影像信息',
          form: {
            [KEYS.key0]: '',
            [KEYS.key1]: '',
            [KEYS.key2]: this.$route.query.id,
            [KEYS.key3]: '',
            [KEYS.key4]: '',
            [KEYS.key10]: '',
            [KEYS.key11]: '',
            [KEYS.key12]: '',
            [KEYS.key13]: '',
            [KEYS.key14]: '',
            [KEYS.key15]: '',
            [KEYS.key16]: '',
            [KEYS.key17]: '',
            [KEYS.key18]: '',

            [KEYS.key19]: '',
            [KEYS.key20]: '',
            [KEYS.key21]: '',
          }
        },
        pop2: {
          flag: false,
          title: '上传图文报告',
          form: {
            [KEYS.key0]: '',
            'name': '',
            'file': '',
          }

        }
      },
      tableData: {
        listInfo1: {
          loading: false,
          height: 500,
          form: {
            patientId: this.$route.query.id,
            pageNum: 1,
            pageSize: 15,
            total: 30,
            pages: 1,
          },
          list: []
        }
      },
      xlsxFile:''
    };
  },
  computed:{
    ...mapGetters('user', ['getUserType']),
  },
  created() {
    this.pageQueryMedicalRecord()
    this.queryPatientOne()
  },
  mounted() {
    
  },
  methods:{
    downFile,
    previewFile,
    copyUrl (a) {
      let routeUrl = this.$router.resolve({
          name: 'managelogin',
          query: {id: a.id}
      });
      let input = document.createElement('input')
      input.style.position = 'fixed'
      input.style.left = '-100%'
      input.style.top = '-100%'
      document.body.appendChild(input)
      input.value = window.SITE_CONFIG['apiURL'] + routeUrl.href
      input.select();
      document.execCommand("copy")
      document.body.removeChild(input)
      this.$message.success('复制链接成功!')
    },
    deletRecordManage (a) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
          const params = { id: a.id, isDeleted: 1 } 
          editMedicalRecord(params).then(res => {
            if (res.data.status !== 200) { return }
            this.$message.success('删除成功!')
            this.pageQueryMedicalRecord()
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });          
        });
    },
    queryPatientOne () {
      queryPatientOne({id: this.prev.id}).then(res => {
        if (res.data.status != 200) { return }
        this.patientInfo = res.data.data
      })
    },
    changeSize (a,b) {
      this.tableData[b].form.pageSize = a
      this.changePage(1, b)
    },
    changePage (a,b) {
      this.tableData[b].form.pageNum = a
      this.pageQueryMedicalRecord()
    },
    pageQueryMedicalRecord () {
      let params = deepCopy(this.tableData.listInfo1.form)
      this.tableData.listInfo1.loading = true
      pageQueryMedicalRecord(params).then(res => {
        this.tableData.listInfo1.loading = false
        if (res.data.status !== 200) { return }
        this.tableData.listInfo1.list = res.data.data.list
        this.tableData.listInfo1.list = this.tableData.listInfo1.list.map(a => {
          if (!a[KEYS.key3]) { a[`${KEYS.key3}3mf`]=[];return a }
          a[`${KEYS.key3}3mf`] = a[KEYS.key3].split(',').map(c => {
            const info = c.split(':')
            return {name:info[0], url: info[1]}
          })
          return a
        })
        this.tableData.listInfo1.list = this.tableData.listInfo1.list.map(a => {
          if (!a[KEYS.key10]) { a[`${KEYS.key10}ct`]=[];return a }
          a[`${KEYS.key10}ct`] = a[KEYS.key10].split(',').map(c => {
            const info = c.split(':')
            return {name:info[0], url: info[1]}
          })
          return a
        })
        this.tableData.listInfo1.form.pageNum = res.data.data.pageNum
        this.tableData.listInfo1.form.total = res.data.data.total
        this.tableData.listInfo1.form.pages = res.data.data.pages

        this.$nextTick(() => {
          this.$refs.eltable.bodyWrapper.scrollTop = 0
        })
      })
    },
    lookModel (a) {
      let routeUrl = this.$router.resolve({
          name: 'modelreports',
          params: {id: a.id}
      });
      window.open(routeUrl.href, '_blank');
    },
    editFormRecordManage (a) {
      this.pop.pop1.flag = true
      this.pop.pop1.title = '编辑影像信息'

      this.fileList3mf = a[`${KEYS.key3}3mf`]
      this.$nextTick(() => {
        for (let i in this.pop.pop1.form) {
          this.pop.pop1.form[i] = a[i]
        }
      })

      this.fileListct = a[`${KEYS.key10}ct`]
      this.$nextTick(() => {
        for (let i in this.pop.pop1.form) {
          this.pop.pop1.form[i] = a[i]
        }
      })

      this.fileList3mfScreenshot = a[`${KEYS.key15}3mfScreenshot`]
      this.$nextTick(() => {
        for (let i in this.pop.pop1.form) {
          this.pop.pop1.form[i] = a[i]
        }
      })

      this.fileListctScreenshot = a[`${KEYS.key16}ctScreenshot`]
      this.$nextTick(() => {
        for (let i in this.pop.pop1.form) {
          this.pop.pop1.form[i] = a[i]
        }
      })
    },
    isPass(form) {
      return new Promise((reslove, reject) => {
        this.$refs[form].validate((valid) => {
          reslove(valid);
        });
      });
    },
    closeAddEdit () {
      this.$refs.addEditFormMedicalRecord.resetFields();
      this.pop.pop1.form[KEYS.key0] = ''
      this.pop.pop1.flag = false
    },
    closePDFPoP(){
      this.$refs.upLoadPDFRecord.resetFields();
      document.getElementById('uploadFile_input').value="";
      this.pop.pop2.form[KEYS.key0] = ''
      this.pop.pop2.flag = false

    },
    onChange (fileList, key) {
      // this.pop.pop1.form[key] = fileList.map(a => `${a.name.replace(/\.[^ .]+$/,'')}:${a.url}`).join(',')
      this.pop.pop1.form[key] = fileList.map(a => `${a.name}:${a.url}`).join(',')
      this.$refs.addEditFormMedicalRecord.validateField(key)
    },
    onChange2(fileList,key){
      this.pop.pop2.form[key] = fileList.map(a => `${a.url}`).join(',')
      this.$refs.upLoadPDFRecord.validateField(key)
    },
    async addMedicalRecord () {
      let isPass = await this.isPass('addEditFormMedicalRecord');
      if (!isPass) {return}
      let params = deepCopy(this.pop.pop1.form)
      if (params.id) {
        editMedicalRecord(params).then(res => {
          if (res.data.status !== 200) { return }
          this.$message.success('编辑成功!')
          this.closeAddEdit()
          this.pageQueryMedicalRecord()
        })
      } else {
        addMedicalRecord(params).then(res => {
          if (res.data.status !== 200) { return }
          this.$message.success('新增成功!')
          this.closeAddEdit()
          this.pageQueryMedicalRecord()
        })
      }
    },
    uploadPDFShow(a){
      this.pop.pop2.flag = true
      this.pop.pop2.title = '上传图文报告'
      this.$nextTick(() => {
        for (let i in this.pop.pop2.form) {
          this.pop.pop2.form[i] = a[i]
        }
      })
    },
    matchType(fileName){
      let suffix = '';
      let result = '';
      try {
        let flieArr = fileName.split('.');
        suffix = flieArr[flieArr.length - 1];
      } catch (err) {
        suffix = '';
      }
      if (!suffix) {
        result = false;
        return result;
      }
      let pdflist = ['pdf'];
      result = pdflist.some(function (item) {
        return item == suffix;
      });
      if (result) {
        result = 'pdf';
        return result;
      }

    },
    getFile(){
      //获取file内容
      let files = this.$refs.fileId.files[0];
      this.xlsxFile = files;
    },
    uploadGraphicReport(){
      if(this.matchType(this.xlsxFile.name)!=='pdf'){
        this.$message.error('请上传pdf格式的文件!')
        return;
      }
      let params = deepCopy(this.pop.pop2.form)
      let formData =  new FormData();
      formData.append("file", this.xlsxFile);
      formData.append("id", params.id);
      formData.append("name", this.patientInfo.name);
      uploadQraphicReport(formData).then(res => {
        if (res.data.status !== 200) { return }
        this.$message.success('上传成功!')
        document.getElementById('uploadFile_input').value="";
        this.closePDFPoP();
        this.pageQueryMedicalRecord()
      })

    },
    preview(row){
     let str='http://localhost:8081/temr/file/filterSkip/downloadFile/11_1634881183591.png';
     //window.open(str,'_blank');
      //window.location.href=str;
      let newwin = window.open('');
      newwin.document.write("<img src="+str+" />");
      //newwin.document.write('<embed src="'+str+'" type="application/pdf" width="100%" height="100%">');
    },
    downloadFile(row){
      let str='http://localhost:8081/temr/file/filterSkip/downloadFile/11_1634881183591.png';
      window.open(str);
    }
  },
  beforeDestroy() {
  },
}
</script>
<style scoped lang="less">
.editMedicalRecord {
  height: 100%;
  padding: 10px 20px 65px 20px;
  display: flex;
  flex-direction: column;
  .cardsBoxInfo {
    height: 125px;
  }
  .record {
    flex: 1;
    .btns {
      position: absolute;
      right: 20px;
      top: -45px;
    }
    /deep/.cards-content {
      display: flex;
      padding-bottom: 65px;
    }
    .tableMain {
      margin-top: 0;
      padding: 0;
      flex: 1;
      width: 100%;
    }
  }
  .addEditMedicalRecord {
    .addEditForm {
      max-height: 650px;
      min-height:130px;
      overflow-y: auto;
      overflow-x: hidden;
    }
    #baseFormBtns.baseFormBtns {
      position: initial;
    }
  }
}
</style>
